package com.nhim.cms.dao;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.stereotype.Repository;

import com.nhim.cms.domain.CustomWidgetPropertyValue;
import com.nhim.core.dao.CoreDAO;

/**
 * A data access object (DAO) providing persistence and search support for
 * ContentType entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see .CustomWidget
 * @author Huy Lieu Ta
 */
@Repository
public class CustomWidgetPropertyValueDAO extends CoreDAO<Integer, CustomWidgetPropertyValue> implements
ICustomWidgetPropertyValueDAO {
	
	// property constants
	public static final String NAME = "name";
	public static final String DATA_TYPE = "dataType";
	public static final String VALUE = "value";
	
	@Autowired
	EntityManagerFactory entityManagerFactory;

	@PostConstruct
	public void init() {
		super.setEntityManagerFactory(entityManagerFactory);
	}
	
	public static CustomWidgetPropertyValueDAO getFromApplicationContext(ApplicationContext ctx) {
		return (CustomWidgetPropertyValueDAO) ctx.getBean(CustomWidgetPropertyValueDAO.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CustomWidgetPropertyValue> findByCustomWidgetInstanceId(
			final Integer id) {
		try {
			final String queryString = "select model from CustomWidgetPropertyValue model where model.customWidgetInstance.id"
					+ "= :propertyValue";
			return getJpaTemplate().executeFind(new JpaCallback<Object>() {
				public Object doInJpa(EntityManager em)
						throws PersistenceException {
					Query query = em.createQuery(queryString);
					query.setParameter("propertyValue", id);
					return query.getResultList();
				}
			});
		} catch (RuntimeException re) {
			logger.error("find by customWidgetInstance Id failed.", re);
			return null;
		}
	}

}
